﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using Quexcel.OpenXML.Interfaces;
using System.IO.Packaging;

namespace Quexcel.OpenXML.Excel.Worksheet
{
    internal class Range : Worksheet, IRange
    {
        private string range;
        private string name;

        internal Range(Quexcel.OpenXML.Excel.Workbook.Workbook workbook, Worksheet worksheet, string name, string range)
            : base(workbook, worksheet)
        {
            this.range = range;
            this.name = name;

            Initialize();
        }

        protected override void Initialize()
        {
            Address startAdd = Utils.Util.GetAddress(range.Split(':')[0]);
            Address endAdd = Utils.Util.GetAddress(range.Split(':')[1]);
            startRowIndex = startAdd.row;
            endRowIndex = endAdd.row;
            startCellIndex = Utils.Util.CellAddressToNumber(startAdd.cell);
            endCellIndex = Utils.Util.CellAddressToNumber(endAdd.cell);
        }

        public override bool AppendRow(string[] dataRow, string[] cellOrder)
        {
            bool isDataInserted = base.AppendRow(dataRow, cellOrder);

            if (isDataInserted)
            {
                string startCell = Utils.Util.CellNumberToAddress(startCellIndex);
                string endCell = Utils.Util.CellNumberToAddress(endCellIndex);

                workbook.GetWriter().ModifyRange(RangeName
                    , String.Format("{0}!${1}${2}:${3}${4}", WorksheetName, startCell, startRowIndex, endCell, endRowIndex));
            }

            return isDataInserted;
        }

        #region IDisposable Members

        void IDisposable.Dispose()
        {
            
        }

        #endregion

        #region IRange Members

        public string RangeName
        {
            get { return this.name; }
        }

        #endregion
    }
}
